//
//  TDAlertView.m
//  EVCLub
//
//  Created by Xuni Inc. on 12/27/12.
//  Copyright (c) 2012 tlm. All rights reserved.
//
#import "Masonry.h"
#import "UIDevice+EV.h"
#import "UIImage+EV.h"
#import "UIView+EV.h"
#import "UIColor+EV.h"
#import "UILabel+EV.h"
#import "TDAlertView.h"
#import <QuartzCore/QuartzCore.h>
#import <QuartzCore/CAAnimation.h>
#define Title_COLOR [UIColor blackColor]
#define Title_FONT  [UIFont systemFontOfSize:18]

#define APP_Window [[UIApplication sharedApplication].delegate window]
#define Key_Window [[UIApplication sharedApplication] keyWindow]
//#define SHOWVIEW APP_Window //[UIApplication sharedApplication].keyWindow
#define SHOWVIEW ((Key_Window.windowLevel > UIWindowLevelAlert)?APP_Window:APP_Window)
#define TDALERTVIEW_IDENTIFIER 5555

static BOOL _isShowed;
@interface TDAlertView ()
{
    NSMutableArray* _marButton;
    IBOutlet UIImageView* _bg;
    UIView* _editingView;
    CGSize _orgSize;
    CGRect _orgFrame;
    CGSize _centerOffset;
    int    _device;
}

@end

@implementation TDAlertView


+ (NSString*)localizedStringForBtnKey:(NSString*)BtnKey
{
    if ([BtnKey isEqualToString:AlertIGotItBtnTitleKey])
    {
        return NSLocalizedStringFromTable(@"知道了", @"TDAlertView", @"按钮 知道了");
    }
    if ([BtnKey isEqualToString:AlertOKBtnTitleKey])
    {
        return NSLocalizedStringFromTable(@"确定",@"TDAlertView" ,@"按钮 确定");
    }
    if ([BtnKey isEqualToString:AlertCancelBtnTitleKey]) {
        return NSLocalizedStringFromTable(@"取消",@"TDAlertView", @"按钮 取消");
    }
    return nil;
}
+ (id)messageBox:(NSString*)tips
{
    TDAlertView* view = [TDAlertView viewWithTitle:nil
                                               message:tips
                                          cancelButton:nil
                                          otherButtons:@[kAlertIGotItBtnTitle]
                                              delegate:nil];
    [view show];
    return view;
}

+ (id)warningMessage:(NSString*)tips
{
    TDAlertView* view = [TDAlertView viewWithWarningTitle:nil
                                                  message:tips
                                             cancelButton:nil
                                              otherButtons:@[kAlertIGotItBtnTitle]
                                                 delegate:nil];
    [view show];
    return view;
}

+ (id)viewWithContentView:(UIView*)contentView cancelButton:(NSString*)cancel otherButtons:(NSArray*)buttons delegate:(id<TDAlertViewDelegate>)delegate
{    
    TDAlertView* view = [UIView ev_viewWithNib:@"TDAlertView" owner:nil];
    [view addContentView:contentView andTitle:nil cancelButton:cancel otherButtons:buttons];
    view.delegate = delegate;
    return view;
}

+ (id)viewWithContentView:(UIView*)contentView withTitle:(NSString*)title cancelButton:(NSString*)cancel otherButtons:(NSArray*)buttons delegate:(id<TDAlertViewDelegate>)delegate
{    
    TDAlertView* view = [UIView ev_viewWithNib:@"TDAlertView" owner:nil];
    [view addContentView:contentView andTitle:title cancelButton:cancel otherButtons:buttons];
    view.delegate = delegate;
    
    return view;
}

+ (id)viewWithTitle:(NSString*)title message:(NSString *)message cancelButton:(NSString*)cancel otherButtons:(NSArray*)buttons delegate:(id<TDAlertViewDelegate>)delegate
{
    TDAlertView* view = [UIView ev_viewWithNib:@"TDAlertView" owner:nil];
    [view addTitle:title leftIcon:nil message:message cancelButton:cancel otherButtons:buttons];
    view.delegate = delegate;
    return view;
}

+ (id)viewWithWarningTitle:(NSString*)title
                   message:(NSString *)message
              cancelButton:(NSString*)cancel
              otherButtons:(NSArray*)buttons
                  delegate:(id<TDAlertViewDelegate>)delegate
{
    TDAlertView* view = [UIView ev_viewWithNib:@"TDAlertView" owner:nil];
    UIImage* left = [UIImage imageNamed:@"alert_icon_warning"];
    [view addTitle:title leftIcon:left message:message cancelButton:cancel otherButtons:buttons];
    view.delegate = delegate;
    return view;
}

+ (id)viewWithTitle:(NSString*)title leftIcon:(UIImage*)leftIcon message:(NSString *)message cancelButton:(NSString*)cancel otherButtons:(NSArray*)buttons delegate:(id<TDAlertViewDelegate>)delegate
{
    TDAlertView* view = [UIView ev_viewWithNib:@"TDAlertView" owner:nil];
    [view addTitle:title leftIcon:leftIcon message:message cancelButton:cancel otherButtons:buttons];
    view.delegate = delegate;
    return view;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.layer.shadowColor = [[UIColor blackColor] CGColor];
        self.layer.shadowOffset = CGSizeMake(0, 2);
        self.layer.shadowOpacity = 0.3;
        self.layer.shouldRasterize = YES;
        self.layer.rasterizationScale = [UIScreen mainScreen].scale;
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)addContentView:(UIView*)contentView andTitle:(NSString*) title cancelButton:(NSString*) cancel otherButtons:(NSArray*) buttons
{
    if (contentView)
    {
        self.contentView = contentView;
        contentView.ev_top = 0;
        self.ev_width = self.contentView.ev_width;
        [self addSubview:self.contentView];
        [_contentView ev_setPosition:CGPointMake(0, 0)];
        
    }
}

- (instancetype)initWithTitle:(NSString *)title
                      message:(NSString *)message
            cancelButtonTitle:(NSString *)cancelButtonTitle
                  clickButton:(TDAlertBlock)block
            otherButtonTitles:(NSArray *)otherButtonTitles {
    
    TDAlertView* view = [UIView ev_viewWithNib:@"TDAlertView" owner:nil];
    [view addTitle:title leftIcon:nil message:message cancelButton:cancelButtonTitle otherButtons:otherButtonTitles];
    view.block = block;
    return view;
}


- (void)addTitle:(NSString*)title leftIcon:(UIImage *)leftIcon message:(NSString *)message cancelButton:(NSString*)cancel otherButtons:(NSArray*)buttons
{
    _strMessage = [message copy];
    _strTitle = [title copy];
    _leftIcon = leftIcon;
    CGFloat y = 5;
    if (_strTitle.length > 0 )
    {
        UIView* titleView = [self addTitleLable];
        y = titleView.ev_bottom;
    }
    UIView* contentView = [UIView ev_viewWithNib:@"AlertViewContent1" owner:nil];
    UIImageView* icon = (UIImageView*)[contentView viewWithTag:226];
    UILabel* messageLable = (UILabel*)[contentView viewWithTag:227];
    messageLable.text = _strMessage;
    if (_leftIcon)
    {
        icon.image = leftIcon;
    }
    else
    {
        icon.hidden = YES;
        CGFloat gap = contentView.ev_width - messageLable.ev_right;
        messageLable.ev_left = gap;
        messageLable.ev_width = contentView.ev_width - 2*gap;
    }
    messageLable.numberOfLines = 0;
    CGFloat width = messageLable.ev_width;
    [messageLable ev_adjustsSizeToFitText:width];
    [messageLable ev_adjustIntegralFrame];
    if (width != messageLable.ev_width)
    {//左右居中
        CGFloat totalWidth = messageLable.ev_width;
        CGFloat gap = (self.ev_width - totalWidth)/2;
        if (!icon.hidden)
        {
            totalWidth += messageLable.ev_left - icon.ev_left;
            gap = (self.ev_width - totalWidth)/2;
            icon.ev_left = gap;
            [icon ev_adjustIntegralFrame];
        }
        messageLable.ev_right = self.ev_width - gap;
        [messageLable ev_adjustIntegralFrame];
    }
    contentView.ev_height = messageLable.ev_top + messageLable.ev_bottom;
    contentView.ev_top = y;
    [contentView ev_adjustIntegralFrame];
    self.ev_height = contentView.ev_bottom;
    [self addSubview:contentView];
    
    [self addCancelButton:cancel otherButtons:buttons];
}

- (void)addCancelButton:(NSString*)cancel otherButtons:(NSArray*)buttons
{
    if (cancel == nil && buttons == nil)
    {
        return;
    }
    NSUInteger btnCount = buttons.count;    
    if (cancel)
    {
        btnCount++;
    }
    _buttonCount = btnCount;
    _marButton = [NSMutableArray arrayWithCapacity:btnCount];
    CGFloat y = self.ev_height;
    UIImageView* gap = [[UIImageView alloc] initWithFrame:CGRectMake(0, y, self.ev_width, 0.5)];
    gap.image = [UIImage imageNamed:@"alert_btn_gap_line"];
    [self addSubview:gap];
    y += gap.ev_height+0.5;
    switch (_buttonCount)
    {
        case 2:
        {
            BOOL bCancel = (cancel != nil);
            NSString* leftTitle = cancel;
            if (leftTitle == nil)
            {
                leftTitle = buttons[0];
            }
            UIButton * left = [self buttonWithTitle:leftTitle isCancel:bCancel longBtn:NO];
            left.ev_top = y;
            left.ev_left = 0;
            left.ev_width = self.ev_width / 2  - 2 * left.ev_left;
            [left ev_adjustIntegralFrame];
            [self addSubview:left];
            [_marButton addObject:left];
            left.accessibilityLabel = @"AlertView_Button_left";
            
            UIButton * right = [self buttonWithTitle:[buttons lastObject] isCancel:NO longBtn:NO];
            right.ev_top = left.ev_top;
            right.ev_left = self.ev_width / 2 + left.ev_left;
            right.ev_width = left.ev_width;
            [right ev_adjustIntegralFrame];
            [self addSubview:right];
            [_marButton addObject:right];
            right.accessibilityLabel = @"AlertView_Button_right";
            y += left.frame.size.height;
            
            UIImageView* gap = [[UIImageView alloc] initWithFrame:CGRectMake(left.ev_right, left.ev_top, 0.5, left.ev_height)];
            gap.image = [UIImage imageNamed:@"alert_btn_gap_line"];
            [self addSubview:gap];
        }
            break;
        default:
        {
            for (int i = buttons.count-1 ; i >= 0; i--)
            {
                if (_marButton.count > 0)
                {
                    UIImageView* gap = [[UIImageView alloc] initWithFrame:CGRectMake(0, y, self.ev_width, 0.5)];
                    gap.image = [UIImage imageNamed:@"alert_btn_gap_line"];
                    [self addSubview:gap];
                    y += gap.ev_height;
                }
                UIButton* button = [self buttonWithTitle:buttons[i] isCancel:NO longBtn:YES];
                button.ev_left = 0;
                button.ev_width = self.ev_width;
                button.ev_top = y;
                [self addSubview:button];
                [_marButton insertObject:button atIndex:0];
                y += button.ev_height;
                button.accessibilityLabel = [NSString stringWithFormat:@"AlertView_Button_%i",i];
            }
            if (cancel)
            {
                if (_marButton.count > 0)
                {
                    UIImageView* gap = [[UIImageView alloc] initWithFrame:CGRectMake(0, y, self.ev_width, 0.5)];
                    gap.image = [UIImage imageNamed:@"alert_btn_gap_line"];
                    [self addSubview:gap];
                    y += gap.ev_height;
                }
                UIButton* button = [self buttonWithTitle:cancel isCancel:YES longBtn:YES];
                button.ev_left = 0;
                button.ev_width = self.ev_width;
                button.ev_top = y;
                [self addSubview:button];
                [_marButton insertObject:button atIndex:0];
                y += button.ev_height;
                button.accessibilityLabel = [NSString stringWithFormat:@"AlertView_Button_Cancel"];
            }
        }
            break;
    }
    self.ev_height = y;
    if ([TDAlertView needObserverKeyboard:_contentView])
    {
        if ([UIDevice ev_iosVersion] < 5.0) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name: UIKeyboardWillShowNotification object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        }
        else
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name: UIKeyboardDidChangeFrameNotification object:nil];
    }

   
  
}

//jjxh added....计算坐标不要每个地方都self.frame写死啊喂。。改起来想屎啊。。。so 加个函数
- (CGRect) getContentViewRect
{
    CGRect ret = [UIScreen mainScreen].bounds;
//    if ([UIDevice isIPad]) {
//        ret.origin.x = (int)((ret.size.width - 782)/2);
//        ret.size.width = 782;
//    }
//    else
    {
        ret.origin.x = 30;
        ret.size.width = ret.size.width - ret.origin.x*2;
    }
    return ret;
}

- (void) center:(UIView*) child toParent:(UIView*) parent
{
    CGRect child_rect  = child.frame;
    CGRect parent_rect = parent.frame;
    if ([child isMemberOfClass:[UILabel class]]) {
        UILabel* label = (UILabel*)child;
        NSString* text = label.text;
		child_rect.size = [text sizeWithAttributes:@{NSFontAttributeName:label.font}];
    }
    child_rect.origin.x = (int)((parent_rect.size.width - child_rect.size.width) / 2);
    child_rect.origin.y = (int)((parent_rect.size.height - child_rect.size.height) / 2);
    [child setFrame:child_rect];
}

- (void) resizeUILabel:(UILabel*) obj
{
    CGRect rect = obj.frame;
	rect.size = [obj.text sizeWithAttributes:@{NSFontAttributeName:obj.font}];
    [obj setFrame:rect];
}

- (UIView*)addTitleLable
{
    NSAssert(_strTitle, @"%s",__FUNCTION__);
    if (_strTitle)
    {
        UILabel *titleLable=[[UILabel alloc] initWithFrame:CGRectMake(0, 15, self.ev_width, 20)];
        [titleLable setTextAlignment:NSTextAlignmentCenter];
        [titleLable setText:_strTitle];
        [titleLable setTextColor:Title_COLOR];
        titleLable.numberOfLines = 0;
        [titleLable setBackgroundColor:[UIColor clearColor]];
        [titleLable setFont:Title_FONT];
        [self addSubview:titleLable];
        return titleLable;
    }
    else
    {
        return nil;
    }
}

- (UIButton*)buttonWithTitle:(NSString*)title isCancel:(BOOL)bCancel longBtn:(BOOL)bLong
{
    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];    
    button.frame = CGRectMake(0, 0, 150, 46);
    button.titleLabel.font = [UIFont systemFontOfSize:14];
    [button setTitle:title forState:UIControlStateNormal];

    NSString* normal = @"alert_btn_ok_normal";
    NSString* hover  = @"alert_btn_ok_hover";
    UIColor* titleColor = [UIColor ev_colorWithHexString:@"#1587CE"];
    
    if (bCancel)
    {
        normal = @"alert_btn_cancel_normal";
        hover  = @"alert_btn_cancel_hover";
        titleColor = [UIColor ev_colorWithHexString:@"#333333"];
    }
    else if(bLong)
    {
        normal = @"alert_btn_long_normal";
        hover  = @"alert_btn_long_hover";
    }
    [button setTitleColor:titleColor forState:UIControlStateNormal];
    UIImage* normalImg = [UIImage ev_resizeableImageNamed:normal];
    [button setBackgroundImage:normalImg forState:UIControlStateNormal];
    UIImage* hoverImg = [UIImage ev_resizeableImageNamed:hover];
    [button setBackgroundImage:hoverImg forState:UIControlStateHighlighted];
    
    [button addTarget:self action:@selector(onButton:) forControlEvents:UIControlEventTouchUpInside];
    return button;
}



- (void)onButton:(UIButton*)sender
{
    NSUInteger index = [_marButton indexOfObject:sender];
    if (index == NSNotFound)
    {
        return;
    }
    BOOL dis = YES;
    if (_delegate && [_delegate respondsToSelector:@selector(shouldDisappearAlertView:onClickedButtonAtIndex:)])
    {
        dis = [_delegate shouldDisappearAlertView:self onClickedButtonAtIndex:index];
    }
    if (dis)
    {
         [self dismissForBtnIndex:index];
    }
    
    if(_block)
    {
        _block(index);
        [self dismissForBtnIndex:index];
    }
}

- (void)ajustOrientationByStatusBarFrameOnView:(UIView*)view
{
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    CGRect rcScreen = [UIScreen mainScreen].bounds;
    CGFloat fWidth = rcScreen.size.width;
    CGFloat fHeight = rcScreen.size.height;
    if (rcScreen.size.height < rcScreen.size.width) {
        fWidth = rcScreen.size.height;
        fHeight = rcScreen.size.width;
    }
    
    CGRect rcProperRect = CGRectMake(0, 0, fWidth, fHeight);
    CGFloat angle = 0;
    switch (orientation) {
        case UIInterfaceOrientationPortraitUpsideDown:
        {
            angle = M_PI;
        }
            break;
            
        case UIInterfaceOrientationLandscapeLeft:
        {
            rcProperRect = CGRectMake(0,0,fHeight,fWidth);
            angle = 3*M_PI_2;
        }
            break;
            
        case UIInterfaceOrientationLandscapeRight:
        {
            rcProperRect = CGRectMake(0,0,fHeight,fWidth);
            angle = M_PI_2;
        }
            break;
            
        default:
            break;
    }
    
    view.frame = rcProperRect;
    view.center = CGPointMake(view.superview.bounds.size.width/2, view.superview.bounds.size.height/2);
    [view ev_adjustIntegralFrame];
    view.transform = CGAffineTransformMakeRotation(angle);
    view.bounds = rcProperRect;
    
    self.frame = _orgFrame;
    self.frame = CGRectMake(0,0,_orgSize.width,_orgSize.height);
    self.center = CGPointMake(view.bounds.size.width/2 + _centerOffset.width,
                              view.bounds.size.height/2 + _centerOffset.height);
    [self ev_adjustIntegralFrame];
}

- (void)onApplicationDidChangeStatusBarFrame:(NSNotification*)notification
{
    // 决定根据状态栏所在的方向实时调整弹出窗的位置
    [self ajustOrientationByStatusBarFrameOnView:self.superview];
}
 
- (void)showInView:(UIView*)supview centerOffset:(CGSize)centerOffset
{
    if (supview == nil)
    {
        return;
    }
    if (_bShowing) {
        return;
    }
    _centerOffset = centerOffset;
    
    _bShowing = YES;
    _isShowed = YES;
    _editingView = [TDAlertView findFirstResponderBeneathView:supview];
    if (_editingView != nil)
    {
        [_editingView resignFirstResponder];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onApplicationDidChangeStatusBarFrame:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
    
    CGRect rcFrame = supview.bounds;
    UIView *emptyView = [[UIView alloc] initWithFrame:rcFrame];
    emptyView.frame = rcFrame;
    UIView* bg = [[UIView alloc] initWithFrame:rcFrame];
    bg.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    bg.backgroundColor = [self maskColor];
    //mark the alert view so that we can find it,the identifier should be unique!
    bg.tag = TDALERTVIEW_IDENTIFIER;
    [emptyView addSubview:bg];
    [supview addSubview:emptyView];
    
    _orgFrame = self.frame;
    
    // 决定根据状态栏所在的方向初始化位置
    _orgSize = self.frame.size;
    [self ajustOrientationByStatusBarFrameOnView:emptyView];
    
    if ([_delegate respondsToSelector:@selector(alertView:willMoveToView:)])
    {
        [_delegate alertView:self willMoveToView:emptyView];
    }
    [emptyView addSubview:self];
    if ([_delegate respondsToSelector:@selector(alertView:didMoveToView:)]) {
        [_delegate alertView:self didMoveToView:emptyView];
    }
    
    // 动画效果
    emptyView.alpha = 0.0f;
    CGRect rcOrg = self.frame;
    CGRect rc = rcOrg;
    rc.origin.y += 50;
    self.frame = rc;
    [UIView animateWithDuration:0.3 animations:^{
        self.frame = rcOrg;
        emptyView.alpha = 1.0f;
    }];
}

-(void)showInView:(UIView*)supview
{
    if(_contentDidAddedBlock){
        _contentDidAddedBlock();
    }
    self.ev_width = self.contentView.ev_width;
    self.ev_height = self.contentView.ev_bottom;
    [self showInView:supview centerOffset:CGSizeZero];
}

- (void) show
{
    if(_contentDidAddedBlock){
        _contentDidAddedBlock();
    }
    self.ev_width = self.contentView.ev_width;
    self.ev_height = self.contentView.ev_bottom;
    if ([[NSThread currentThread] isMainThread]) {
        [self showInView:SHOWVIEW
            centerOffset:CGSizeMake(0, [UIApplication sharedApplication].statusBarHidden?0: (MIN([UIApplication sharedApplication].statusBarFrame.size.height, [UIApplication sharedApplication].statusBarFrame.size.width)/2))];
    }
    else{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showInView:SHOWVIEW
                centerOffset:CGSizeMake(0, [UIApplication sharedApplication].statusBarHidden?0: (MIN([UIApplication sharedApplication].statusBarFrame.size.height, [UIApplication sharedApplication].statusBarFrame.size.width)/2))];
        });
    }
}

-(void) dismissForBtnIndex:(NSInteger)btnIndex;
{
    if (!_bShowing) {
        return;
    }
    _bShowing = NO;
    _isShowed = NO;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
    
    if (_editingView != nil)
    {
        if (_editingView.superview) {
            [_editingView becomeFirstResponder];
        }
        _editingView = nil;
    }
    if ([_delegate respondsToSelector:@selector(alertView:willMoveToView:)])
    {
        [_delegate alertView:self willMoveToView:nil];
    }
    
    if (_animationDisabled)
    {
        UIView* view = self.superview;
        if ([_delegate respondsToSelector:@selector(alertView:didMoveToView:)]) {
            [_delegate alertView:self didMoveToView:nil];
        }
        if ([_delegate respondsToSelector:@selector(TDAlertView:didDismissWithButtonIndex:)])
        {
            [_delegate TDAlertView:self didDismissWithButtonIndex:btnIndex];
        }
        
        [self removeFromSuperview];        
        [view removeFromSuperview];
        self.contentDidAddedBlock = nil;
    }
    else
    {
        [self transitionToRemoveFromSuperview:0.25 onBtn:btnIndex];
    }
     [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)dismiss
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self dismissForBtnIndex:-1];
    });
}

-(void)dismissIntemidialy
{
    [self dismissForBtnIndex:-1];
}

-(void) transitionToRemoveFromSuperview:(NSTimeInterval)duration onBtn:(NSInteger)index
{
    UIView* emptyView = self.superview;
    CGRect rcOrg = self.frame;
    [UIView animateWithDuration:duration animations:^{
        emptyView.alpha = 0.0f;
        
        CGRect rc = rcOrg;
        rc.origin.y += 50;
        self.frame = rc;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        self.contentDidAddedBlock = nil;
        [emptyView removeFromSuperview];
        if (!_delegate && [_delegate respondsToSelector:@selector(alertView:didMoveToView:)]) {
            [_delegate alertView:self didMoveToView:nil];
        }
        if (_delegate && [_delegate respondsToSelector:@selector(TDAlertView:didDismissWithButtonIndex:)])
        {
            [_delegate TDAlertView:self didDismissWithButtonIndex:index];
        }
    }];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/
+ (UIView*)findFirstResponderBeneathView:(UIView*)view
{
    // Search recursively for first responder
    for (UIView *childView in view.subviews) {
        if ([childView respondsToSelector:@selector(isFirstResponder)] && [childView isFirstResponder]) {
            return childView;
        }
        UIView *result = [self findFirstResponderBeneathView:childView];
        if (result != nil)
        {
            return result;
        }
    }
    return nil;
}

+ (BOOL)needObserverKeyboard:(UIView*)view
{
    if ([view isKindOfClass:[UITextField class] ] || [view isKindOfClass:[UITextView class]])
    {
        return YES;
    }
    for (UIView* sub in view.subviews)
    {
        if ([TDAlertView needObserverKeyboard:sub])
        {
            return YES;
        }
    }
    return NO;
}

- (NSString*)titleForButton:(NSUInteger)index
{
    if (index > _marButton.count) {
        return nil;
    }
    UIButton* btn = _marButton[index];
    return [btn titleForState:UIControlStateNormal];
}

+ (BOOL)hasAlertView{
    return [SHOWVIEW viewWithTag:TDALERTVIEW_IDENTIFIER]?YES:NO;
}

+(BOOL) isExist{
    
   return (YES == _isShowed);
}

- (void)setHideDefaultBackground:(BOOL)hideDefaultBackground {
    _bg.hidden = hideDefaultBackground;
}

- (BOOL)hideDefaultBackground {
    return _bg.hidden;
}

- (UIColor *)maskColor {
    return _maskColor ?: [UIColor colorWithWhite:0.0 alpha:0.7];
}

#pragma mark UINotifications
-(void)keyboardWillShow:(NSNotification *)notification{
    CGRect keyboardRect = [[notification userInfo][UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [self handleKeyBoardShow:keyboardRect];
}

-(void)keyboardChange:(NSNotification*)notification
{
    
    CGRect keyboardRect = [[notification userInfo][UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect rcKeyWindow =  self.window.bounds;
    if ((keyboardRect.origin.x < 0 || keyboardRect.origin.y < 0) ||
        (keyboardRect.origin.x == 0 && keyboardRect.origin.y == rcKeyWindow.size.height) ||
        (keyboardRect.origin.y == 0 && keyboardRect.origin.x == rcKeyWindow.size.width))
        [self keyboardWillHide:notification];
    else
        [self keyboardWillShow:notification];
}

-(void)keyboardWillHide:(NSNotification *)notification{
  //  XLLog(@"will Hide");
  //  self.frame = _orgFrame;
    [self centerMySelf];
}

-(void) handleKeyBoardShow:(CGRect) keyboardRect
{
    
   CGRect rcKeyWindow =  self.window.bounds;
    CGFloat keyBoardHeight = keyboardRect.size.height;
    CGFloat keyWindowHeight = rcKeyWindow.size.height;
    CGFloat useableHeight = keyWindowHeight - keyBoardHeight;
    if (useableHeight > self.frame.origin.y + self.frame.size.height + 10) {
        return;
    }
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
        keyBoardHeight = keyboardRect.size.width;
        keyWindowHeight = rcKeyWindow.size.width;
    }
    CGFloat fixOriginY = keyWindowHeight - keyBoardHeight - self.frame.size.height-10;
    
    _orgFrame = self.frame;
    [self ev_setPosition:CGPointMake(self.frame.origin.x
                                  , fixOriginY)];
}

-(void) centerMySelf
{
    
   CGRect rcKeyWindow =  self.window.bounds;
    CGFloat keyWindowHeight = rcKeyWindow.size.height;
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
        keyWindowHeight = rcKeyWindow.size.width;
    }
    CGFloat fixOriginY = (keyWindowHeight - self.frame.size.height)/2;
    
    _orgFrame = self.frame;
    [self ev_setPosition:CGPointMake(self.frame.origin.x
                                  , fixOriginY)];
}

-(void)awakeFromNib
{
    [super awakeFromNib];
    [_bg setImage:[UIImage ev_resizeableImageNamed:@"alert_bkg"]];
    //[self setFrame:[self getContentViewRect]];
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    UIView *view = [super hitTest:point withEvent:event];
    if (self.delegate && [self.delegate respondsToSelector:@selector(alertView:didClickOutside:)])
    {
        [self.delegate alertView:self didClickOutside:view];
    }
    return view;
}

@end
